 #include "ThreadPool.h"

ThreadPool::ThreadPool(unsigned int size) {
  for (unsigned int i = 0; i < size; ++i) {
    m_workers.emplace_back(std::thread([this]() {
      while (true) {
        std::function<void()> task;
        {
          std::unique_lock<std::mutex> lock(m_mutex);
          m_cv.wait(lock, [this]() { return m_stop || !m_tasks.empty(); });
          if (m_stop && m_tasks.empty()) {
            return;
          }
          task = m_tasks.front();
          m_tasks.pop();
        }
        task();
      }
    }));
  }
}

ThreadPool::~ThreadPool() {
  {
    std::unique_lock<std::mutex> lock(m_mutex);
    m_stop = true;
  }
  m_cv.notify_all();
  for (std::thread &th : m_workers) {
    if (th.joinable()) {
      th.join();
    }
  }
}
